﻿using System;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Net.Mail;

namespace xundh.Common
{
   public static class Sms
    {
        #region 通过动易短信通发送短信
        /// <summary>
        /// 通过动易短信通发送短信
        /// </summary>
        /// <param name="sendNum">接收号码</param>
        /// <param name="sendContent">接收内容</param>
        /// <param name="sendType">是否定时发送，0为否（默认），1为定时</param>
        /// <param name="sendTime">定时发送时间</param>
        /// <param name="reserve">自定义，如发送者</param>
        /// <returns></returns>
        public static string SendMessage(string smsUserName, string smsMD5Key, string sendNum, string sendContent, string sendType, string sendTime, string reserve)
        {
            string smsGateUrl = "http://sms.powereasy.net/MessageGate2/MessageGate.aspx";
            string str = "xundh" + Guid.NewGuid().ToString();
            sendNum = sendNum.Replace(",", "\r\n");
            StringBuilder builder = new StringBuilder();
            builder.Append("ID=");
            builder.Append(str);
            builder.Append("&UserName=");
            builder.Append(smsUserName);//动易短信通的用户名称
            builder.Append("&SendNum=");
            builder.Append(sendNum);//接收号码
            builder.Append("&Content=");
            builder.Append(sendContent);//接收内容
            builder.Append("&SendTiming=0");
            builder.Append("&SendTime=");
            builder.Append(sendTime);//定时发送时间
            builder.Append("&Reserve=");
            builder.Append(reserve);//自定义，如发送者
            builder.Append("&MD5String=");
            builder.Append(MD5gb2312(str + smsUserName + smsMD5Key + sendNum + sendContent + sendType + sendTime));
            string s = builder.ToString();
            Uri requestUri = new Uri(smsGateUrl);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
            request.Referer = smsGateUrl;
            request.UserAgent = "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.2;   SV1;   .NET   CLR   1.1.4322";
            request.Headers.Add("Accept-Language:   zh-cn");
            request.ServicePoint.Expect100Continue = false;
            byte[] bytes = Encoding.Default.GetBytes(s);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }
            Stream responseStream = ((HttpWebResponse)request.GetResponse()).GetResponseStream();
            Encoding encoding = Encoding.Default;
            StreamReader reader = new StreamReader(responseStream, encoding);
            string str3 = reader.ReadToEnd();
            reader.Close();
            return str3;
        }
        #endregion

        #region 动易短信通使用的MD5
        /// <summary>
        /// 动易短信通使用的MD5
        /// </summary>
        /// <param name="input">要加密的字符</param>
        /// <returns></returns>
        private static string MD5gb2312(string input)
        {
            //using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
            //{
            //    return BitConverter.ToString(provider.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(input))).Replace("-", "").ToLower();
            //}
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(input));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString().ToUpper();

        }
        #endregion

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Annex">附件，如果没有则null</param>
        /// <param name="ToEmail">Email地址</param>
        /// <param name="EmailTitle">标题</param>
        /// <param name="EmailContent">内容</param>
        /// <returns></returns>
        public static sendMailStatus SendEmail(string FromEmail, string EmailPwd, string ToEmail, string EmailTitle, string EmailContent, string EmailSmtp)
        {

            MailMessage mm = new MailMessage();
            //发件人
            mm.From = new MailAddress(FromEmail, FromEmail);

            //收件人(可以是多个)
            mm.To.Add(new MailAddress(ToEmail));

            //主题
            mm.Subject = EmailTitle;

            //邮件正文

            mm.Body = EmailContent;
            mm.IsBodyHtml = true;
            SmtpClient sc = new SmtpClient();

            //设置SMTP主机的名称或IP地址
            sc.Host = EmailSmtp;

            string User = FromEmail;
            string PassWord = EmailPwd;

            //设置用于验证发件人身份的凭据
            sc.Credentials = new System.Net.NetworkCredential(User, PassWord);
            try
            {
                sc.Send(mm);
                return sendMailStatus.Success;
            }
            catch (Exception)
            {
                return sendMailStatus.Fail;
            }


        }

        /// <summary>
        /// 发送飞信
        /// </summary>
        /// <param name="fromNo">发送的号码</param>
        /// <param name="fromPass">飞信密码</param>
        /// <param name="toNo">接收手机号码</param>
        /// <param name="sendContent">内容</param>
        /// <returns></returns>
        public static string sendFesion(string fromNo, string fromPass, string toNo, string sendContent)
        {
            try
            {
                StringBuilder url = new StringBuilder();
                url.Append("http://sms.api.bz/fetion.php?");
                url.Append("username=" + fromNo);
                url.Append("&password=" + fromPass);
                url.Append("&sendto=" + toNo);
                url.Append("&message=" + sendContent);


                HttpWebRequest request = WebRequest.Create(url.ToString()) as HttpWebRequest;
                Stream stream = null;
                StreamReader reader = null;
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                string line = reader.ReadToEnd();
                return line; 
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }

}
public enum sendMailStatus { Success, Fail }